package com.vikutorika.filter;

import com.vikutorika.entity.UserInfo;
import com.vikutorika.service.UserService;
import com.vikutorika.servlet.UserServlet;
import com.vikutorika.util.CookieUtil;
import com.vikutorika.vo.ResultVo;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/index.jsp")
public class AutoLoginFilter implements Filter {
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
                System.out.println("AutoLoginFilter");
                HttpServletRequest request = (HttpServletRequest) servletRequest;
                HttpServletResponse response = (HttpServletResponse) servletResponse;
                HttpSession session = request.getSession();
                if (session.getAttribute("userInfo") != null)
                        filterChain.doFilter(servletRequest, servletResponse);
                String autoLogin = CookieUtil.getCookieValue(request, "autoLogin");
                if(autoLogin != null && autoLogin.equals("true")) {
                        String phone = CookieUtil.getCookieValue(request, "phone");
                        String password = CookieUtil.getCookieValue(request, "password");
                        UserInfo userInfo = new UserInfo();
                        userInfo.setPhone(phone);
                        userInfo.setPassword_hash(password);
                        UserService userService = new UserService();
                        ResultVo resultVo = userService.login(userInfo);
                        if (resultVo.getCode().equals("500"))
                                response.sendRedirect("/Vikutorika/login.html");
                        session.setAttribute("userInfo", resultVo.getData());
                }
                filterChain.doFilter(servletRequest, servletResponse);
        }
}
